package com.dodock.banglapapers.server.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsListDW extends DefaultHandler  {

	public static final String TAG_ITEM_PARENT = "channel";
	public static final String TAG_ITEM = "item";
	public static final String TAG_ITEM_TITLE = "title";
	public static final String TAG_ITEM_LINK = "link";
	public static final String TAG_ITEM_DETAILS = "details";
	public static final String TAG_ITEM_CATEGORY = "category";
	public static final String TAG_ITEM_IMAGE = "image";
	public static final String TAG_ITEM_IMAGE_URL = "url";
	public static final String TAG_ITEM_GUID = "guid";

	public static final String TAG_ITEM_SCROLLNEWS = "scrollNews";
	public static final String TAG_ITEM_THUMB = "thumb";
	public static final String TAG_ITEM_PUBDATE = "pubDate";
	public static final String TAG_ITEM_CAPTION = "caption";
	public static final String TAG_ITEM_THUMBNAIL = "thumbnail";
	
	JsonArray array;
	boolean itemParsing;
	String lastTagName;
	JsonObject news;
	private String characters;
	
	
	
	public String GenerateNewsList(String categoryid) {
		
		try{
			if(categoryid.equals("top")){
				return generateNewsListFromXmlFeed("rss-ben-11973");
			}
			else if(categoryid.equals("sports")){
				return generateNewsListFromXmlFeed("rss-ben-11974");
			}
			else if(categoryid.equals("science")){
				return generateNewsListFromXmlFeed("rss-ben-11976");
			}
			else if(categoryid.equals("women")){
				return generateNewsListFromXmlFeed("rss-ben-30781");
			}
			else if(categoryid.equals("social")){
				return generateNewsListFromXmlFeed("rss-ben-11977");
			}
			else if(categoryid.equals("discovergermany")){
				return generateNewsListFromXmlFeed("rss-ben-12492");
			}
			else if(categoryid.equals("culture")){
				return generateNewsListFromXmlFeed("rss-ben-11978");
			}
			else if(categoryid.equals("germanyhigherstudy")){
				return generateNewsListFromXmlFeed("rss-ben-13795");
			}	
		}
		catch(Exception ex){
			return "[]";
		}
		
		
		return "[]";
	}

	
	private String generateNewsListFromXmlFeed(String nativeid) throws IOException, SAXException, ParserConfigurationException{
		array = new JsonArray();
		itemParsing = false;
		lastTagName = null;
		
		URL url = new URL(String.format("http://rss.dw-world.de/xml/%s", nativeid));
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
		StringBuilder xmlString = new StringBuilder();
		String line;
        while ((line = reader.readLine()) != null) {
        	
        	line = line.replaceAll("&amp;#39;", "'");
        	line = line.replaceAll("&#39;", "'");
        	line = line.replaceAll("-&-", "-&amp;-");
        	xmlString.append(line);
        }
        reader.close();
        
        
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(new java.io.ByteArrayInputStream(xmlString.toString().getBytes("UTF-8")), this);
		
		return array.toString();
	}
	
	
	public void startElement(String namespaceURI, 
            String localName,
            String qualifiedName,
            Attributes attributes) 
            		throws SAXException {
			lastTagName = qualifiedName;
			if (lastTagName.equalsIgnoreCase(TAG_ITEM)) {
				itemParsing = true;
				news = new JsonObject();
			}
	}
	
	public void endElement(String namespaceURI, 
            String simpleName,
            String qualifiedName) 
            throws SAXException {
		
		if (qualifiedName.equalsIgnoreCase(TAG_ITEM)) {
			itemParsing = false;
			array.add(news);
		} 
		lastTagName = null;
	}
	
	public void characters(char buf[], int offset, int len) 
            throws SAXException {
            characters = new String(buf, offset, len);
            
            if (lastTagName != null) {
				if (lastTagName.equalsIgnoreCase(TAG_ITEM_TITLE)) {
					if (itemParsing) {
						news.addProperty("title", characters);
					}
				} else if (lastTagName.equalsIgnoreCase(TAG_ITEM_LINK)) {
					if (itemParsing){
						news.addProperty("sharelink", characters);
						int i = characters.lastIndexOf('/') + 1;
						int f = characters.indexOf('?', i);
						news.addProperty("id", characters.substring(i, f));
					}
				} 
			}
    }
	
}
